<template>
  <div class="merchant-list">
    <el-card class="mb-4">
      <el-form :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item label="活动标题">
          <el-input v-model="searchForm.title" placeholder="请输入活动标题" clearable class="w-60" />
        </el-form-item>
        <!-- <el-form-item label="商家标题">
                                                            <el-input v-model="searchForm.title" placeholder="请输入商家标题" clearable class="w-60" />
                                                        </el-form-item>
                                                        <el-form-item label="联系电话">
                                                            <el-input v-model="searchForm.phone" placeholder="请输入联系电话" clearable class="w-60" />
                                                        </el-form-item> -->
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
          <el-button type="primary" @click="handleAdd" style="margin-left: 30px" v-has="'activity:save'">新增活动</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  
    <!-- 表格 -->
    <el-table v-loading="loading" :data="tableData" border style="width: 100%;margin-top:15px">
      <el-table-column prop="id" label="序号" width="70" />
      <el-table-column prop="title" label="活动标题" />
      <el-table-column prop="activityAddress" label="活动地址" />
      <el-table-column prop="coverImage" label="活动图片" width="120">
        <template #default="{ row }">
          <el-image v-if="row.coverImage" style="width: 80px; height: 80px" :src="row.coverImage"
            :preview-src-list="[row.coverImage]" fit="cover" />
        </template>
      </el-table-column>
      <!-- <el-table-column prop="description" label="活动介绍" /> -->
      <el-table-column prop="startTime" label="活动有效期" width="200">
        <template #default="{ row }">
          <span>{{ row.startTime }} - {{ row.endTime }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="quota" label="活动名额" show-overflow-tooltip />
      <el-table-column prop="registered" label="已报名人数" />
      <el-table-column prop="activityAddress" label="活动地址" />
      <el-table-column prop="paymentType" label="付款方式" width="120">
        <template #default="{ row }">
          <el-tag v-if="row.paymentType == '免费'" type="info">免费</el-tag>
          <el-tag v-if="row.paymentType == '积分'" type="warning">积分</el-tag>
          <el-tag v-if="row.paymentType == '金额'" type="warning">金额</el-tag>
          <el-tag v-if="row.paymentType == '微信支付'" type="success">微信支付</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="paymentAmount" label="付款(积分或金额)" />

      <!-- <el-table-column prop="createBy" label="创建人" /> -->
      <!-- <el-table-column prop="createTime" label="创建时间" /> -->
      <!-- <el-table-column prop="updateBy" label="更新人" /> -->
      <!-- <el-table-column prop="updateTime" label="更新时间" /> -->
      <el-table-column label="操作" width="240" fixed="right">
        <template #default="{ row }">
          <el-button type="text" :style="{color:row.isHot ? '#f56c6c' : '#409EFF'}" v-has="'activity:update'"
            @click="setHotActivity(row.id,row.isHot)">{{row.isHot ? '取消热门' : '设置热门'}}</el-button>
          <el-button type="text" v-has="'activity:update'" @click="openDialog(row)">报名人数</el-button>
          <el-button type="text" v-has="'activity:update'" @click="handleEdit(row)">编辑</el-button>
          <el-button type="text" style="color: #f56c6c" v-has="'activity:delete'"
            @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  
    <!-- 分页 -->
    <div class="pagination">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page.sync="currentPage" :page-sizes="[10, 20, 50, 100]" :page-size="pageSize"
        layout="total, sizes, prev, pager, next" :total="total">
      </el-pagination>
    </div>
  
    <!-- 新增/编辑弹窗 -->
    <el-dialog :close-on-click-modal="false" :title="dialogType === 'add' ? '新增活动' : '编辑活动'" :visible.sync="dialogVisible"
      width="80%" @close="resetForm">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="活动标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入商家标题" />
        </el-form-item>
        <el-form-item label="活动封面图" prop="coverImage">
          <el-upload class="image-uploader" :headers="headers" :action="$uploadUrl" :show-file-list="false"
            :on-success="handleUploadSuccess" :before-upload="beforeUpload">
            <img v-if="form.coverImage" :src="form.coverImage" class="uploaded-image" />
            <div v-else class="upload-placeholder">
              <i class="el-icon-plus"></i>
              <div class="upload-text">点击上传活动图片</div>
            </div>
          </el-upload>
          <!-- <div class="form-tip">建议尺寸：200x200px，支持jpg、png格式</div> -->
        </el-form-item>
        <el-form-item label="活动轮播图" prop="imageUrl">
          <el-upload class="image-uploader" :headers="headers" :action="$uploadUrl" :show-file-list="false"
            :on-success="handleIconSuccess1" :before-upload="beforeUpload">
            <div class="flex_flex">
              <div v-for="item,index in form.imageUrl" :key="index" class="image-item">
                <img :src="item" class="uploaded-image" />
                <div class="delete-image" @click="handleDeleteImage(index)">删除</div>
              </div>
              <div class="upload-placeholder">
                <i class="el-icon-plus"></i>
                <div class="upload-text">点击上传图片</div>
              </div>
            </div>
          </el-upload>
        </el-form-item>
        <el-form-item label="有效期" prop="effectDate">
          <el-date-picker v-model="form.effectDate" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"
            type="daterange" value-format="yyyy-MM-dd" class="w-full">
            <!--  HH:mm:ss   :default-time="['00:00:00', '23:59:59']" datetimerange-->
          </el-date-picker>
        </el-form-item>
        <el-form-item label="付款方式" prop="paymentType">
          <el-radio-group v-model="form.paymentType">
            <el-radio :label="0">免费</el-radio>
            <el-radio :label="1">积分</el-radio>
            <el-radio :label="2">金额</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item :label="'付款'+(form.paymentType === 1 ? '积分' : '金额')" prop="paymentAmount" v-if="form.paymentType != 0">
          <el-input v-model="form.paymentAmount" type="number" :placeholder="'请输入付款'+(form.paymentType === 1 ? '积分' : '金额')" />

        </el-form-item>
        <el-form-item label="活动名额" prop="quota">
          <el-input v-model="form.quota" placeholder="请输入活动名额" />
        </el-form-item>
        <el-form-item label="已报名人数" prop="registered">
          <el-input v-model="form.registered" placeholder="请输入已报名人数" />
        </el-form-item>
        <el-form-item label="活动地址" prop="activityAddress">
          <el-input v-model="form.activityAddress" placeholder="请输入活动地址" />
        </el-form-item>
        <el-form-item label="活动详情" prop="activityDetails">
          <EditorBar style="width: 100%" v-model="form.activityDetails" :catchData="catchDataAgreement"></EditorBar>
        </el-form-item>
        <el-form-item label="活动规则" prop="activityRules">
          <EditorBar style="width: 100%" v-model="form.activityRules" :catchData="catchDataAgreement1"></EditorBar>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  
    <!-- 报名人数弹窗 -->
    <el-dialog :close-on-click-modal="false" title="报名人数列表" :visible.sync="registrationDialogVisible"
      @close="registrationDialogVisible =false" width="80%">
      <div class="dialog_height">
        <div class="registration-header">
          <div>活动标题：{{ currentActivity.title }}</div>
          <div>活动时间：{{ currentActivity.startTime }} - {{ currentActivity.endTime }}</div>
          <div>报名人数：{{ currentActivity.registered }}</div>
        </div>
          <el-button @click="exportData" v-has="'userCoupon:export'">导出</el-button>
  
        <el-table :data="registrationList" border style="width: 100%; margin-top: 15px">
          <el-table-column prop="id" label="序号" width="70" />
          <el-table-column prop="activityTitle" label="活动名称" />
          <!-- <el-table-column prop="userId" label="报名帐号" /> -->
          <el-table-column prop="name" label="联系人姓名" />
          <el-table-column prop="phone" label="联系人电话" />
          <!-- <el-table-column prop="paymentAmount" label="支付金额" /> -->
          <!-- <el-table-column prop="isRefunded" label="是否退款">
            <template #default="{ row }">
              <el-tag v-if="row.isRefunded" type="success">已退款</el-tag>
              <el-tag v-else type="info">未退款</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="refundTime" label="退款时间" /> -->
          <el-table-column label="状态" width="100">
            <template #default="{ row }">
              <el-tag v-if="typeof row.status === 'number'"
                :type="row.status === 0 ? 'info' : row.status === 1 ? 'success' : 'danger'">{{ row.status === 0 ? '待确认' :
                row.status === 1 ? '已确认' : '已取消' }}</el-tag>
              <el-tag v-else>{{ row.status }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="审核" width="100">
            <template #default="{ row }">
              <el-button type="text" v-if="typeof row.status === 'number' && row.status == 0"
                @click="handleAudit(row)">审核</el-button>
              <el-button type="text" v-else-if="row.status == '待确认'" @click="handleAudit(row)">审核</el-button>
              <!-- <el-button type="text" @click="handleRefund(row)" v-if="!row.isRefunded && row.isPaid == '已支付'">退款</el-button> -->
            </template>
          </el-table-column>
          <!-- <el-table-column label="操作" width="120">
                          <template #default="{ row }">
                            <el-button 
                              v-if="row.status === 0" 
                              type="text" 
                              @click="confirmRegistration(row.id)"
                            >确认</el-button>
                            <el-button 
                              type="text" 
                              style="color: #f56c6c" 
                              @click="cancelRegistration(row.id)"
                            >取消报名</el-button>
                          </template>
                        </el-table-column> -->
        </el-table>
      </div>
    </el-dialog>
    <el-dialog :close-on-click-modal="false" title="审核" :visible.sync="auditDialogVisible" width="80%">
      <el-form :model="formAudit" :rules="rulesAudit" ref="formAuditRef" label-width="100px" class="dialog_height">
        <el-form-item label="审核状态" prop="status">
          <el-radio-group v-model="formAudit.status">
            <el-radio :label="1">通过</el-radio>
            <el-radio :label="2">拒绝</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="拒绝原因" prop="reviewReason" v-if="formAudit.status == 2">
          <el-input type="textarea" rows="3" placeholder="请输入拒绝原因" v-model="formAudit.reviewReason">
          </el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="auditDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitAudit">确认</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import EditorBar from "@/components/WangEnduit.vue";
import { Loading } from 'element-ui';
export default {
  name: 'MerchantList',
  components: {
    EditorBar
  },
  data() {
    return {
      formAudit: {
        status: '',
        reviewReason: '',
      },
      rulesAudit: {
        reviewReason: [{ required: true, message: '请输入拒绝原因', trigger: 'blur' }],
        status: [{ required: true, message: '请选择审核状态', trigger: 'blur' }],
      },
      headers: {
        'token': localStorage.getItem('token')
      },
      // 搜索表单
      searchForm: {
        title: '',
      },
      // 分页
      currentPage: 1,
      pageSize: 10,
      total: 0,
      // 表格数据
      tableData: [],
      loading: false,
      // 弹窗相关
      dialogVisible: false,
      dialogType: 'add', // add 或 edit
      uploadUrl: '', // 上传地址
      form: {
        title: '',
        paymentType: 0, // 0: 免费, 1: 积分, 2: 金额
        paymentAmount: 0,
        imageUrl: [],
        coverImage: '',
        effectDate: [],
        quota: '',
        registered: 0,
        activityDetails: '',
        activityRules: '',
        activityAddress: ''
      },
      // 表单校验规则
      rules: {
        name: [
          { required: true, message: '请输入商家名称', trigger: 'blur' },
          { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
        ],
        title: [
          { required: true, message: '请输入商家标题', trigger: 'blur' },
          { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
        ],
        address: [
          { required: true, message: '请输入商家地址', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入联系电话', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
        ],
        coverImage: [
          { required: true, message: '请上传活动封面图', trigger: 'blur' }
        ],
        imageUrl: [
          { required: true, message: '请上传活动轮播图', trigger: 'blur' }
        ],
      },

      registrationDialogVisible: false,
      currentActivity: {},
      registrationList: [],
      auditObj: {},
      auditDialogVisible: false
    }
  },
  created() {
    this.getList()
  },
  methods: {

    async exportData() {
      // 显示加载中
      const loading = this.$loading({
        lock: true,
        text: '导出中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });

      try {
        // 准备导出参数
        const params = {
          // page: 1,
          // size: 10000,
          activityId: this.currentActivity.id
          // condition: {
          //   userId: this.searchForm.userId,
          //   couponId: this.searchForm.couponId,
          //   writeOffStatus: this.searchForm.writeOffStatus,
          //   isExpired: this.searchForm.isExpired,
          //   shopId: this.searchForm.shopId
          // }
        };

        // 调用导出API
        const { data } = await this.$api.exportUserActivity(params);

        // 创建下载链接
        if (data) {
          // 如果返回的是文件流
          if (data instanceof Blob) {
            const blob = new Blob([data]);
            const url = window.URL.createObjectURL(blob);
            const link = document.createElement('a');
            link.href = url;
            link.download = this.currentActivity.title + '.xlsx'; // 设置下载文件名
            link.click();
            window.URL.revokeObjectURL(url);
            this.$message.success('导出成功');
          }
          // 如果返回的是下载链接
          else if (typeof data === 'string') {
            this.$message.success('导出成功');
            window.open(data, '_blank');
          }
          // 如果返回的是其他格式的数据
          else {
            this.$message.success('导出成功');
            console.log(data, '导出数据');
          }
        } else {
          this.$message.warning('没有可导出的数据');
        }
      } catch (error) {
        console.error('导出失败', error);
        this.$message.error('导出失败：' + (error.message || '未知错误'));
      } finally {
        // 关闭加载中
        loading.close();
      }
    },
    handleRefund(row) {
      this.$confirm('确认退款吗？', '提示', {
        type: 'warning'
      }).then(async () => {
        try {
          await this.$api.refundActivity(row.id)
          this.$message.success('退款成功')
          this.getList()
          this.registrationDialogVisible = false
        } catch (error) {
          console.error('退款失败：', error)
          this.$message.error('退款失败')
        }
      }).catch(() => { })
    },
    submitAudit() {
      const loading = this.$loading({
          lock: true,
          text: '申请中...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.3)'
        });    
      this.$refs.formAuditRef.validate(async (valid) => {
        if (valid) {
          try {
            await this.$api.ctivitySignUpaudit({
              userId: this.auditObj.userId,
              activityId: this.auditObj.activityId,
              status: this.formAudit.status,
              reviewReason: this.formAudit.reviewReason,
              orderNo:this.auditObj.orderNo
            })
            this.$message.success('审核成功')
            this.auditDialogVisible = false;
            this.getRegistrationList()
            this.getList()
            loading.close();
          } catch (error) {
            loading.close();
            console.error('审核失败：', error)
            this.$message.error('审核失败')
          }
        }
      })
    },
    handleAudit(row) {
      this.auditObj = row;
      this.auditDialogVisible = true
    },
    async setHotActivity(id, ishot) {
      await this.$api.setHotActivity(id, ishot == 1 ? 0 : 1)
      this.$message.success('设置成功')
      this.getList()
    },
    // 打开报名人数弹窗
    openDialog(row) {
      this.registrationDialogVisible = true
      this.currentActivity = row
      this.getRegistrationList()
    },

    // 获取报名人数列表
    async getRegistrationList() {
      try {
        const { data } = await this.$api.getActivitySignUpCount(this.currentActivity.id)
        console.log(data);
        this.registrationList = data.result.registrations
      } catch (error) {
        console.error('获取报名列表失败：', error)
        this.$message.error('获取报名列表失败')
      }
    },

    // 确认报名
    // async confirmRegistration(id) {
    //   try {
    //     await this.$api.confirmRegistration(id)
    //     this.$message.success('确认成功')
    //     this.getRegistrationList()
    //   } catch (error) {
    //     console.error('确认失败：', error)
    //     this.$message.error('确认失败')
    //   }
    // },

    // 取消报名
    // async cancelRegistration(id) {
    //   this.$confirm('确认取消该用户的报名吗？', '提示', {
    //     type: 'warning'
    //   }).then(async () => {
    //     try {
    //       await this.$api.cancelRegistration(id)
    //       this.$message.success('取消报名成功')
    //       this.getRegistrationList()
    //     } catch (error) {
    //       console.error('取消报名失败：', error)
    //       this.$message.error('取消报名失败')
    //     }
    //   }).catch(() => {})
    // },


    catchDataAgreement1(val) {
      this.form.activityRules = val;
    },
    catchDataAgreement(val) {
      this.form.activityDetails = val;
    },
    // 获取列表数据
    async getList() {
      this.loading = true
      try {
        const { data } = await this.$api.getActivityList({
          page: this.currentPage,
          size: this.pageSize,
          condition: {
            ...this.searchForm
          }
        })
        this.tableData = data.result.records
        this.total = data.result.total
      } catch (error) {
        console.error('获取商家列表失败：', error)
      } finally {
        this.loading = false
      }
    },

    // 搜索
    handleSearch() {
      this.currentPage = 1
      this.getList()
    },

    // 重置搜索
    resetSearch() {
      this.searchForm = {
        title: '',
      }
      this.handleSearch()
    },

    // 分页相关
    handleSizeChange(val) {
      this.pageSize = val
      this.getList()
    },

    handleCurrentChange(val) {
      this.currentPage = val
      this.getList()
    },

    // 新增
    handleAdd() {
      this.dialogType = 'add'
      this.dialogVisible = true
    },

    // 编辑
    handleEdit(row) {
      this.dialogType = 'edit'
      this.form = {
        id: row.id,
        title: row.title,
        paymentType: row.paymentType == '免费' ? 0 : row.paymentType == '积分' ? 1 : row.paymentType == '金额' || row.paymentType == '微信支付' ? 2 : 3,
        paymentAmount: row.paymentAmount,
        coverImage: row.coverImage,
        imageUrl: row.imageUrl ? row.imageUrl : [],
        effectDate: [row.startTime, row.endTime],
        quota: row.quota,
        registered: row.registered,
        activityDetails: row.activityDetails,
        activityRules: row.activityRules,
        activityAddress: row.activityAddress
      }
      this.dialogVisible = true
    },

    // 删除
    handleDelete(row) {
      this.$confirm('确认删除该活动吗？', '提示', {
        type: 'warning'
      }).then(async () => {
        try {
          await this.$api.deleteActivity(row.id)
          this.$message.success('删除成功')
          this.getList()
        } catch (error) {
          console.error('删除失败：', error)
        }
      }).catch(() => { })
    },

    // 上传相关
    handleUploadSuccess(res) {
      this.form.coverImage = res.result.filePath
    },
    // 图片上传成功回调
    async handleIconSuccess1(res) {
      this.form.imageUrl.push(res.result.filePath)
    },
    handleDeleteImage(index) {
      this.form.imageUrl.splice(index, 1)
    },

    beforeUpload(rawFile) {
      const imgSize = rawFile.size / 1024 / 1024 < 10
      const imgType = ['image/jpeg', 'image/png', 'image/gif']
      if (!imgType.includes(rawFile.type))
        message.notifyWarning('上传图片不符合所需的格式！')
      if (!imgSize) message.notifyWarning(`上传图片大小不能超过 10M！`)
      return imgType.includes(rawFile.type) && imgSize
    },

    // 提交表单
    handleSubmit() {
      this.$refs.formRef.validate(async (valid) => {
        if (valid) {
          try {
            const params = {
              ...this.form,
              startTime: this.form.effectDate[0],
              endTime: this.form.effectDate[1]
            }
            if(params.paymentType == 0) {
              params.paymentAmount = 0
            }
            delete params.effectDate
            if (this.dialogType === 'add') {
              await this.$api.addActivity(params)
              this.$message.success('新增成功')
            } else {
              await this.$api.updateActivity(params)
              this.$message.success('编辑成功')
            }
            this.dialogVisible = false
            this.getList()
          } catch (error) {
            console.error(this.dialogType === 'add' ? '新增失败：' : '编辑失败：', error)
          }
        }
      })
    },

    // 重置表单
    resetForm() {
      if (this.$refs.formRef) {
        this.$refs.formRef.resetFields()
      }
      this.form = {
        name: '',
        paymentAmount: 0,
        paymentType: 0, // 0: 免费, 1: 积分
        title: '',
        imageUrl: [],
        coverImage: '',
        address: '',
        phone: '',
        activityDetails: '',
        activityRules: '',
        activityAddress: ''
      }
    }
  }
}
</script>

<style scoped lang="scss">
.dialog_height {
  height: 50vh;
  overflow: hidden;
  overflow-y: auto;
}

.image-item {
  position: relative;
}

.delete-image {
  position: absolute;
  bottom: 15px;
  right: 0px;
  width: 100%;
  height: 20px;
  font-size: 14px;
  background: rgba(0, 0, 0, 0.5);
  color: #fff;
  cursor: pointer;
  z-index: 1000;
  line-height: 20px;
}

.flex_flex {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.image-uploader {
  .uploaded-image {
    width: 140px;
    height: 140px;
    object-fit: cover;
    border-radius: 4px;
  }

  .upload-placeholder {
    width: 140px;
    height: 140px;
    border: 1px dashed #d9d9d9;
    border-radius: 4px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    cursor: pointer;
    transition: border-color 0.3s;

    &:hover {
      border-color: #409EFF;
    }

    .el-icon-plus {
      font-size: 28px;
      color: #8c939d;
    }

    .upload-text {
      font-size: 12px;
      color: #8c939d;
      margin-top: 8px;
    }
  }
}

.merchant-list {
  padding: 20px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}

.avatar {
  width: 120px;
  height: 120px;
  display: block;
}

.registration-header {
  background-color: #f5f7fa;
  padding: 15px;
  border-radius: 4px;
  margin-bottom: 15px;
}

.registration-header div {
  margin-bottom: 8px;
  font-size: 14px;
}

.registration-header div:last-child {
  margin-bottom: 0;
}
</style>